import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/components" as Components
import "qrc:/qml/styles" as Styles

/**
 * @brief 仿真车辆管理弹窗（重构版）
 * @details 集合新增、编辑、删除等常用操作，优化布局和信息层次
 */
Components.CustomDialog {
    id: root
    title: qsTr("仿真车辆管理")
    dialogWidth: 1000
    dialogHeight: 680
    showOkButton: false
    showCancelButton: false

    property bool isEditMode: false
    property var vehicleData: null
    property var vehicleListModel: null

    property int selectedAgvNumber: -1
    property string searchText: ""
    property bool isValid: agvNumberField.text.length > 0 &&
                          agvNameField.text.length > 0 &&
                          initialStationField.text.length > 0

    signal vehicleSaved(var data)
    signal vehicleDeleted(int agvNumber)

    contentItem: RowLayout {
        anchors.fill: parent
        spacing: Styles.Theme.spacingLarge

        // ==================== 左侧车辆列表 ====================
        Rectangle {
            id: leftPanel
            Layout.preferredWidth: 300
            Layout.fillHeight: true
            radius: Styles.Theme.radiusNormal
            color: Styles.Theme.backgroundAlternate
            border.color: Styles.Theme.border
            border.width: 1

            ColumnLayout {
                id: leftPanelContent
                anchors.fill: parent
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingSmall

                // 标题区域
                Text {
                    text: qsTr("车辆列表")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeMedium
                    font.weight: Font.Bold
                }

                // 搜索框
                Components.SearchBar {
                    id: searchBar
                    Layout.fillWidth: true
                    placeholderText: qsTr("搜索编号或名称...")
                    onTextSearched: function(value) { root.searchText = value }
                    onCleared: root.searchText = ""
                }

                // 统计信息
                Text {
                    text: qsTr("共 %1 辆车辆").arg(getFilteredCount())
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }

                // 车辆列表
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: "transparent"
                    border.color: Styles.Theme.border
                    border.width: 1
                    radius: Styles.Theme.radiusSmall

                    ScrollView {
                        id: vehicleListScroll
                        anchors.fill: parent
                        anchors.margins: 1
                        clip: true
                        ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
                        WheelHandler {
                            acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
                            onWheel: function(event) { root.handleWheel(vehicleListScroll, event) }
                        }

                        ListView {
                            id: vehicleListView
                            model: vehicleListModel ? vehicleListModel : 0
                            spacing: Styles.Theme.spacingSmall
                            topMargin: Styles.Theme.spacingSmall
                            bottomMargin: Styles.Theme.spacingSmall
                            leftMargin: Styles.Theme.spacingSmall
                            rightMargin: Styles.Theme.spacingSmall

                            delegate: Item {
                                width: vehicleListView.width - Styles.Theme.spacingNormal
                                height: filterMatches ? cardRect.implicitHeight : 0
                                visible: filterMatches

                                property bool filterMatches: root.matchesFilter(model.agvNumber, model.name)

                                Rectangle {
                                    id: cardRect
                                    anchors.fill: parent
                                    implicitHeight: cardLayout.implicitHeight + 16
                                    radius: Styles.Theme.radiusSmall
                                    color: root.selectedAgvNumber === model.agvNumber
                                           ? Styles.Theme.backgroundSelected
                                           : Styles.Theme.surface
                                    border.color: root.selectedAgvNumber === model.agvNumber
                                                  ? Styles.Theme.primary
                                                  : Styles.Theme.border
                                    border.width: root.selectedAgvNumber === model.agvNumber ? 2 : 1

                                    ColumnLayout {
                                        id: cardLayout
                                        anchors.left: parent.left
                                        anchors.right: parent.right
                                        anchors.top: parent.top
                                        anchors.margins: 8
                                        spacing: 6

                                        // 第一行：编号 + 在线状态
                                        RowLayout {
                                            Layout.fillWidth: true
                                            spacing: 6

                                            Text {
                                                text: qsTr("AGV %1").arg(model.agvNumber || "-")
                                                color: Styles.Theme.textPrimary
                                                font.pixelSize: 13
                                                font.weight: Font.Bold
                                            }

                                            Item { Layout.fillWidth: true }

                                            Rectangle {
                                                Layout.preferredWidth: 6
                                                Layout.preferredHeight: 6
                                                radius: 3
                                                color: model.isOnline ? Styles.Theme.success : Styles.Theme.textTertiary
                                            }

                                            Text {
                                                text: model.isOnline ? qsTr("在线") : qsTr("离线")
                                                color: model.isOnline ? Styles.Theme.success : Styles.Theme.textSecondary
                                                font.pixelSize: 11
                                            }
                                        }

                                        // 第二行：名称
                                        Text {
                                            text: model.name || qsTr("未命名")
                                            color: Styles.Theme.textSecondary
                                            font.pixelSize: 11
                                            elide: Text.ElideRight
                                            Layout.fillWidth: true
                                            Layout.maximumWidth: cardLayout.width
                                        }

                                        // 第三行：位置 + 电量
                                        RowLayout {
                                            Layout.fillWidth: true
                                            spacing: 8

                                            Text {
                                                text: model.currentStation || qsTr("--")
                                                color: Styles.Theme.textSecondary
                                                font.pixelSize: 10
                                                elide: Text.ElideRight
                                                Layout.fillWidth: true
                                            }

                                            Rectangle {
                                                Layout.preferredWidth: 40
                                                Layout.preferredHeight: 16
                                                radius: 3
                                                color: Qt.alpha(root.getBatteryColor(model.batteryLevel || 0), 0.15)
                                                border.color: root.getBatteryColor(model.batteryLevel || 0)
                                                border.width: 1

                                                Text {
                                                    anchors.centerIn: parent
                                                    text: (model.batteryLevel || 0) + "%"
                                                    color: root.getBatteryColor(model.batteryLevel || 0)
                                                    font.pixelSize: 9
                                                    font.weight: Font.Bold
                                                }
                                            }
                                        }
                                    }

                                    MouseArea {
                                        anchors.fill: parent
                                        cursorShape: Qt.PointingHandCursor
                                        onClicked: root.selectVehicle(index, model.agvNumber)
                                    }
                                }
                            }

                            // 空状态
                            Item {
                                visible: vehicleListView.count === 0 || getFilteredCount() === 0
                                anchors.centerIn: parent
                                width: parent.width
                                height: parent.height

                                ColumnLayout {
                                    anchors.centerIn: parent
                                    spacing: Styles.Theme.spacingSmall

                                    Text {
                                        text: "🚛"
                                        font.pixelSize: 36
                                        Layout.alignment: Qt.AlignHCenter
                                        opacity: 0.5
                                    }

                                    Text {
                                        text: root.searchText.length > 0 ? qsTr("无匹配车辆") : qsTr("暂无车辆")
                                        color: Styles.Theme.textSecondary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        Layout.alignment: Qt.AlignHCenter
                                    }
                                }
                            }
                        }
                    }
                }

                // 新增按钮
                Components.ActionButton {
                    Layout.fillWidth: true
                    text: qsTr("+ 新增车辆")
                    buttonType: "primary"
                    onClicked: root.beginCreateMode()
                }
            }
        }

        // ==================== 右侧编辑区域 ====================
        ColumnLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: Styles.Theme.spacingNormal

            // ===== 固定头部 =====
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: headerLayout.implicitHeight + Styles.Theme.spacingNormal * 2
                radius: Styles.Theme.radiusNormal
                color: isEditMode ? Qt.alpha(Styles.Theme.success, 0.08) : Qt.alpha(Styles.Theme.warning, 0.08)
                border.color: isEditMode ? Styles.Theme.success : Styles.Theme.warning
                border.width: 1

                RowLayout {
                    id: headerLayout
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    spacing: Styles.Theme.spacingNormal

                    // 状态图标
                    Rectangle {
                        Layout.preferredWidth: 48
                        Layout.preferredHeight: 48
                        radius: 24
                        color: isEditMode ? Qt.alpha(Styles.Theme.success, 0.15) : Qt.alpha(Styles.Theme.warning, 0.15)
                        border.color: isEditMode ? Styles.Theme.success : Styles.Theme.warning
                        border.width: 2

                        Text {
                            anchors.centerIn: parent
                            text: isEditMode ? "✏️" : "➕"
                            font.pixelSize: 24
                        }
                    }

                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 2

                        Text {
                            text: isEditMode ? qsTr("编辑车辆") : qsTr("新增车辆")
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeLarge
                            font.weight: Font.Bold
                        }

                        Text {
                            text: isEditMode
                                  ? qsTr("正在编辑 AGV%1 - %2").arg(agvNumberField.text || "-").arg(agvNameField.text || qsTr("未命名"))
                                  : qsTr("填写下方表单创建新的仿真车辆")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }
                    }

                    Rectangle {
                        Layout.preferredWidth: 90
                        Layout.preferredHeight: 28
                        radius: Styles.Theme.radiusSmall
                        color: isEditMode ? Styles.Theme.success : Styles.Theme.warning

                        Text {
                            anchors.centerIn: parent
                            text: isEditMode ? qsTr("编辑模式") : qsTr("新建模式")
                            color: Styles.Theme.textOnPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            font.weight: Font.Bold
                        }
                    }
                }
            }

            // ===== 可滚动表单区域 =====
            ScrollView {
                id: formScrollView
                Layout.fillWidth: true
                Layout.fillHeight: true
                clip: true
                ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
                WheelHandler {
                    acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
                    onWheel: function(event) { root.handleWheel(formScrollView, event) }
                }

                ColumnLayout {
                    width: formScrollView.availableWidth
                    spacing: Styles.Theme.spacingLarge

                    // 基础信息
                    Rectangle {
                        Layout.fillWidth: true
                        implicitHeight: basicInfoLayout.implicitHeight + Styles.Theme.spacingLarge * 2
                        radius: Styles.Theme.radiusNormal
                        color: Styles.Theme.backgroundAlternate
                        border.color: Styles.Theme.border
                        border.width: 1

                        ColumnLayout {
                            id: basicInfoLayout
                            anchors.fill: parent
                            anchors.margins: Styles.Theme.spacingLarge
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: qsTr("基础信息")
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeMedium
                                font.weight: Font.Bold
                            }

                            GridLayout {
                                Layout.fillWidth: true
                                columns: 2
                                rowSpacing: Styles.Theme.spacingNormal
                                columnSpacing: Styles.Theme.spacingNormal

                                // 车辆编号
                                Text {
                                    text: qsTr("车辆编号 *")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                TextField {
                                    id: agvNumberField
                                    Layout.fillWidth: true
                                    placeholderText: qsTr("请输入车辆编号")
                                    enabled: !isEditMode
                                    color: Styles.Theme.textPrimary
                                    background: Rectangle {
                                        color: agvNumberField.enabled ? Styles.Theme.surface : Styles.Theme.backgroundAlternate
                                        border.color: agvNumberField.activeFocus ? Styles.Theme.primary : Styles.Theme.border
                                        border.width: 1
                                        radius: Styles.Theme.radiusSmall
                                    }
                                    validator: IntValidator { bottom: 1; top: 9999 }
                                }

                                // 车辆名称
                                Text {
                                    text: qsTr("车辆名称 *")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                TextField {
                                    id: agvNameField
                                    Layout.fillWidth: true
                                    placeholderText: qsTr("请输入车辆名称")
                                    color: Styles.Theme.textPrimary
                                    background: Rectangle {
                                        color: Styles.Theme.surface
                                        border.color: agvNameField.activeFocus ? Styles.Theme.primary : Styles.Theme.border
                                        border.width: 1
                                        radius: Styles.Theme.radiusSmall
                                    }
                                }

                            }
                        }
                    }

                    // 位置信息
                    Rectangle {
                        Layout.fillWidth: true
                        implicitHeight: locationLayout.implicitHeight + Styles.Theme.spacingLarge * 2
                        radius: Styles.Theme.radiusNormal
                        color: Styles.Theme.backgroundAlternate
                        border.color: Styles.Theme.border
                        border.width: 1

                        ColumnLayout {
                            id: locationLayout
                            anchors.fill: parent
                            anchors.margins: Styles.Theme.spacingLarge
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: qsTr("位置信息")
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeMedium
                                font.weight: Font.Bold
                            }

                            GridLayout {
                                Layout.fillWidth: true
                                columns: 2
                                rowSpacing: Styles.Theme.spacingNormal
                                columnSpacing: Styles.Theme.spacingNormal

                                // 地图名称
                                Text {
                                    text: qsTr("地图名称 *")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                TextField {
                                    id: initialMapField
                                    Layout.fillWidth: true
                                    placeholderText: qsTr("请输入地图名称")
                                    text: "XP2F"
                                    color: Styles.Theme.textPrimary
                                    background: Rectangle {
                                        color: Styles.Theme.surface
                                        border.color: initialMapField.activeFocus ? Styles.Theme.primary : Styles.Theme.border
                                        border.width: 1
                                        radius: Styles.Theme.radiusSmall
                                    }
                                }

                                // 初始站点
                                Text {
                                    text: qsTr("初始站点 *")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                TextField {
                                    id: initialStationField
                                    Layout.fillWidth: true
                                    placeholderText: qsTr("请输入初始站点")
                                    color: Styles.Theme.textPrimary
                                    background: Rectangle {
                                        color: Styles.Theme.surface
                                        border.color: initialStationField.activeFocus ? Styles.Theme.primary : Styles.Theme.border
                                        border.width: 1
                                        radius: Styles.Theme.radiusSmall
                                    }
                                }

                                // 初始朝向
                                Text {
                                    text: qsTr("初始朝向")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: Styles.Theme.spacingSmall

                                    Slider {
                                        id: initialHeadingSlider
                                        Layout.fillWidth: true
                                        from: 0
                                        to: 360
                                        value: 0
                                        stepSize: 15
                                    }

                                    Text {
                                        text: initialHeadingSlider.value.toFixed(0) + "°"
                                        color: Styles.Theme.textPrimary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        font.weight: Font.Bold
                                        Layout.preferredWidth: 45
                                    }
                                }
                            }
                        }
                    }

                    // 硬件参数
                    Rectangle {
                        Layout.fillWidth: true
                        implicitHeight: hardwareLayout.implicitHeight + Styles.Theme.spacingLarge * 2
                        radius: Styles.Theme.radiusNormal
                        color: Styles.Theme.backgroundAlternate
                        border.color: Styles.Theme.border
                        border.width: 1

                        ColumnLayout {
                            id: hardwareLayout
                            anchors.fill: parent
                            anchors.margins: Styles.Theme.spacingLarge
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: qsTr("硬件参数")
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeMedium
                                font.weight: Font.Bold
                            }

                            GridLayout {
                                Layout.fillWidth: true
                                columns: 2
                                rowSpacing: Styles.Theme.spacingNormal
                                columnSpacing: Styles.Theme.spacingNormal

                                // 初始电量
                                Text {
                                    text: qsTr("初始电量")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: Styles.Theme.spacingSmall

                                    Slider {
                                        id: batteryLevelSlider
                                        Layout.fillWidth: true
                                        from: 0
                                        to: 100
                                        value: 90
                                        stepSize: 5
                                    }

                                    Text {
                                        text: batteryLevelSlider.value.toFixed(0) + "%"
                                        color: root.getBatteryColor(batteryLevelSlider.value)
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        font.weight: Font.Bold
                                        Layout.preferredWidth: 45
                                    }
                                }

                                // 最大速度
                                Text {
                                    text: qsTr("最大速度")
                                    color: Styles.Theme.textPrimary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: Styles.Theme.spacingSmall

                                    TextField {
                                        id: maxSpeedField
                                        Layout.fillWidth: true
                                        placeholderText: qsTr("最大速度")
                                        text: "800"
                                        color: Styles.Theme.textPrimary
                                        background: Rectangle {
                                            color: Styles.Theme.surface
                                            border.color: maxSpeedField.activeFocus ? Styles.Theme.primary : Styles.Theme.border
                                            border.width: 1
                                            radius: Styles.Theme.radiusSmall
                                        }
                                        validator: IntValidator { bottom: 100; top: 2000 }
                                    }

                                    Text {
                                        text: qsTr("mm/s")
                                        color: Styles.Theme.textSecondary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // ===== 固定底部操作栏 =====
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: bottomBar.implicitHeight + Styles.Theme.spacingNormal * 2
                radius: Styles.Theme.radiusNormal
                color: Styles.Theme.backgroundAlternate
                border.color: Styles.Theme.border
                border.width: 1

                RowLayout {
                    id: bottomBar
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        Layout.fillWidth: true
                        text: isEditMode
                              ? qsTr("修改后点击“保存”按钮")
                              : qsTr("填写完成后点击“创建”按钮")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }

                    Components.ActionButton {
                        text: isEditMode ? qsTr("删除车辆") : qsTr("重置表单")
                        buttonType: isEditMode ? "danger" : "secondary"
                        enabled: isEditMode || agvNumberField.text.length > 0 || agvNameField.text.length > 0
                        onClicked: {
                            if (isEditMode) {
                                root.deleteCurrentVehicle()
                            } else {
                                root.beginCreateMode()
                            }
                        }
                    }

                    Components.ActionButton {
                        text: qsTr("取消")
                        buttonType: "secondary"
                        onClicked: root.close()
                    }

                    Components.ActionButton {
                        text: isEditMode ? qsTr("保存修改") : qsTr("创建车辆")
                        buttonType: "primary"
                        enabled: isValid
                        onClicked: root.saveVehicle()
                    }
                }
            }
        }
    }

    // ==================== 辅助函数 ====================
    function matchesFilter(agvNumber, name) {
        if (!searchText || searchText.length === 0)
            return true

        const query = searchText.toLowerCase()
        return (agvNumber && agvNumber.toString().indexOf(query) !== -1) ||
               ((name || "").toLowerCase().indexOf(query) !== -1)
    }

    function getFilteredCount() {
        if (!vehicleListModel) return 0
        if (!searchText || searchText.length === 0)
            return vehicleListModel.rowCount()

        let count = 0
        for (let i = 0; i < vehicleListModel.rowCount(); i++) {
            const data = vehicleListModel.getAgvData(i)
            if (data && matchesFilter(data.agvNumber, data.name)) {
                count++
            }
        }
        return count
    }

    function handleWheel(scrollView, wheel) {
        if (!scrollView || !scrollView.contentItem) {
            return
        }

        const flickable = scrollView.contentItem
        const maxY = Math.max(0, flickable.contentHeight - flickable.height)
        flickable.contentY = Math.max(0, Math.min(maxY, flickable.contentY - wheel.angleDelta.y))
        wheel.accepted = true
    }

    function getBatteryColor(level) {
        if (level < 20) return Styles.Theme.danger
        if (level < 40) return Styles.Theme.warning
        return Styles.Theme.success
    }

    function selectVehicle(index, agvNumber) {
        if (!vehicleListModel) {
            console.warn("SimulationVehicleEditor: vehicleListModel unavailable")
            return
        }

        const data = vehicleListModel.getAgvData(index)
        if (!data) return

        loadVehicleData(data)
        selectedAgvNumber = agvNumber
    }

    function beginCreateMode() {
        reset()
    }

    function openForCreate() {
        beginCreateMode()
        open()
    }

    function loadVehicleData(data) {
        if (!data) return

        isEditMode = true
        vehicleData = data

        agvNumberField.text = (data.agvNumber || data.id || "").toString()
        agvNameField.text = data.name || ""
        initialMapField.text = data.initialMap || data.currentMap || "XP2F"
        initialStationField.text = data.initialStation || data.currentStation || ""
        initialHeadingSlider.value = data.heading || data.angle || 0
        batteryLevelSlider.value = data.batteryLevel || 90
        maxSpeedField.text = data.maxSpeed ? data.maxSpeed.toString() : "800"
        selectedAgvNumber = parseInt(agvNumberField.text)
    }

    function saveVehicle() {
        const data = {
            agvNumber: parseInt(agvNumberField.text),
            name: agvNameField.text,
            initialMap: initialMapField.text,
            initialStation: initialStationField.text,
            heading: initialHeadingSlider.value,
            batteryLevel: batteryLevelSlider.value,
            maxSpeed: parseInt(maxSpeedField.text)
        }

        // 调用 C++ 后端创建/更新仿真车辆
        if (GlobalVehicleViewModel) {
            if (isEditMode) {
                GlobalVehicleViewModel.updateSimulationVehicle(data)
            } else {
                GlobalVehicleViewModel.createSimulationVehicle(data)
            }
        }

        vehicleSaved(data)
        close()
    }

    function deleteCurrentVehicle() {
        if (!isEditMode || agvNumberField.text.length === 0) {
            return
        }

        const agvNumber = parseInt(agvNumberField.text)

        // 调用 C++ 后端删除仿真车辆
        if (GlobalVehicleViewModel) {
            GlobalVehicleViewModel.deleteSimulationVehicle(agvNumber)
        }

        vehicleDeleted(agvNumber)
        close()
    }

    function reset() {
        agvNumberField.text = ""
        agvNameField.text = ""
        initialMapField.text = "XP2F"
        initialStationField.text = ""
        initialHeadingSlider.value = 0
        batteryLevelSlider.value = 90
        maxSpeedField.text = "800"
        isEditMode = false
        vehicleData = null
        selectedAgvNumber = -1
    }
}
